package com.ruoyi.industry.service.impl;

import java.util.*;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.District;
import com.ruoyi.industry.domain.ProjectPark;
import com.ruoyi.industry.domain.SpaceIndustry;
import com.ruoyi.industry.mapper.*;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.industry.domain.ProjectLand;
import com.ruoyi.industry.service.IProjectLandService;

import javax.servlet.http.HttpServletResponse;

/**
 * 土地Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-08
 */
@Service
public class ProjectLandServiceImpl implements IProjectLandService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectAuctionServiceImpl.class);

    @Autowired
    private ProjectLandMapper projectLandMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private RemoteFileService remoteFileService;
    /**
     * 查询土地
     *
     * @param id 土地主键
     * @return 土地
     */
    @Override
    public ProjectLand selectProjectLandById(Long id)
    {
        return projectLandMapper.selectProjectLandById(id);
    }

    /**
     * 查询土地列表
     *
     * @param projectLand 土地
     * @return 土地
     */
    @Override
    public List<ProjectLand> selectProjectLandList(ProjectLand projectLand)
    {
//        //所属城市
//        List<Long> districtIds = new ArrayList<Long>();
//        if (projectLand.getCityId()!=null){
//            districtIds.add(projectLand.getCityId());
//            projectLand.setCityIds(districtIds);
//        }else if (projectLand.getCityId()==null && projectLand.getProvinceId() != null){
//            //查询省份下的城市
//            districtIds.addAll(districtMapper.selectDistrictIdList(projectLand.getProvinceId()));
//            districtIds.add(projectLand.getProvinceId());
//            projectLand.setCityIds(districtIds);
//        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectLand.setSupplyUserId(SecurityUtils.getUserId());
//        }
        List<ProjectLand> projectLands = projectLandMapper.selectProjectLandListz(projectLand);
//        for (ProjectLand land : projectLands) {
//            SysUser sysUser = spaceIndustryMapper.selectSysUserById(land.getServicePhone());
//            if (sysUser!=null) {
//                land.setContactName(sysUser.getNickName());
//                land.setContactPhone(sysUser.getPhonenumber());
//            }
//        }
        return projectLands;
    }

    /**
     * 新增土地
     *
     * @param projectLand 土地
     * @return 结果
     */
    @Override
    public int insertProjectLand(ProjectLand projectLand)
    {
        projectLand.setSupplyUserId(SecurityUtils.getUserId());
        if (projectLand.getApprovalState() == null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectLand.setApprovalState(1L);
//            } else {
                projectLand.setApprovalState(0L);
//            }
        }
        projectLand.setCreateTime(DateUtils.getNowDate());
        projectLand.setSerialNumber(IdUtils.fastSimpleUUID());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectLand, spaceIndustry);
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectLand.getCreateTime());
        spaceIndustry.setSpaceId(projectLand.getSerialNumber());
        spaceIndustry.setSupplyUserId(projectLand.getSupplyUserId());
        spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
        return projectLandMapper.insertProjectLand(projectLand);
    }
    private static void extracted(ProjectLand projectLand, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(8);
        spaceIndustry.setReleaseType(projectLand.getReleaseType());
        spaceIndustry.setApprovalState(projectLand.getApprovalState());
        spaceIndustry.setProvinceId(projectLand.getProvinceId());//省份
        spaceIndustry.setCityId(projectLand.getCityId());//城市
//        spaceIndustry.setAreaId();//区域
//        spaceIndustry.setSupplyType(projectLand.getSupplyType());//服务类型
        spaceIndustry.setParkId(String.valueOf(projectLand.getParkId()));
//        spaceIndustry.setHeating(projectLand.getBuildHeating());//供暖
//        spaceIndustry.setRefrig(projectLand.getBuildRefrig());//制冷
//        spaceIndustry.setPower(projectLand.getBuildPower());//电力
//        spaceIndustry.setGas(projectLand.getBuildGas());//燃气
        spaceIndustry.setLeasePrice(projectLand.getLandPrice());//出售价格
        spaceIndustry.setSellPrice(projectLand.getLandPrice());//租赁价格
        spaceIndustry.setCoverResource(projectLand.getCoverResource());//封面资源
        spaceIndustry.setSpaceName(projectLand.getLandName());//园区名称
        spaceIndustry.setSpaceAllSize(projectLand.getLandAllSize());//空间总面积
        spaceIndustry.setTop(projectLand.getTop());//置顶
        spaceIndustry.setRecomState(projectLand.getRecomState());
    }
    /**
     * 修改土地
     *
     * @param projectLand 土地
     * @return 结果
     */
    @Override
    public int updateProjectLand(ProjectLand projectLand)
    {
        if (projectLand.getApprovalState() == null) {
            projectLand.setApprovalState(0L);
        }
        projectLand.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectLand,spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectLand.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectLand.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByLandId(spaceIndustry);
        return projectLandMapper.updateProjectLand(projectLand);
    }

    /**
     * 批量删除土地
     *
     * @param ids 需要删除的土地主键
     * @return 结果
     */
    @Override
    public int deleteProjectLandByIds(Long[] ids)
    {
        List<String> pathList = new ArrayList<>();
        for (ProjectLand projectLand : projectLandMapper.selectProjectLandByIds(ids)) {
            spaceIndustryMapper.deleteSpaceRecomById("土地",projectLand.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectLand.getVrResource(),
                    projectLand.getImgResource(),
                    projectLand.getCoverResource(),
                    projectLand.getVrcover(),
                    projectLand.getQrCode()
            );
        }
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectLandIds(ids);
        return projectLandMapper.deleteProjectLandByIds(ids);
    }

    /**
     * 删除土地信息
     *
     * @param id 土地主键
     * @return 结果
     */
    @Override
    public int deleteProjectLandById(Long id)
    {
        ProjectLand projectLand = projectLandMapper.selectProjectLandById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectLand.getVrResource(),
                projectLand.getImgResource(),
                projectLand.getCoverResource(),
                projectLand.getVrcover(),
                projectLand.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("土地",projectLand.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectLandId(id);
        return projectLandMapper.deleteProjectLandById(id);
    }

    /**
     * 查询土地
     *
     * @param spaceId 编号
     * @param show
     * @return 结果
     */
    @Override
    public Map<String, Object> selectProjectLandByNumber(String spaceId, boolean show) {
        ProjectLand projectLand = projectLandMapper.selectProjectLandByNumber(spaceId);
        if (SecurityUtils.getUserId()!=null&&SecurityUtils.getUserId()!=0) {
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectLandMapper.updatePageViews(spaceId);
            }
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(), spaceId);
            if (list != null && list.size() != 0) {
                projectLand.setCollectState(1L);
            } else {
                projectLand.setCollectState(0L);
            }
        }else {
            projectLand.setCollectState(0L);
        }
        if (projectLand.getProvinceId()!=null){
            District district = districtMapper.selectDistrictById(projectLand.getProvinceId());
            projectLand.setCityName(district.getName());
        }
        if (projectLand.getCityId()!=null){
            District district = districtMapper.selectDistrictById(projectLand.getCityId());
            projectLand.setCityName(projectLand.getCityName()+district.getName());
        }
        if (projectLand.getAreaId()!=null){
            District district = districtMapper.selectDistrictById(projectLand.getAreaId());
            projectLand.setCityName(projectLand.getCityName()+district.getName());
        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectLand.getServicePhone());
        if (sysUser!=null){
            projectLand.setContactName(sysUser.getNickName());
            projectLand.setContactPhone(sysUser.getPhonenumber());
            projectLand.setQrCode(sysUser.getCodePic());
        }
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectLand.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("space",projectLand);
        if (projectLand.getParkId()!=null) {
            ProjectPark projectPark = projectParkMapper.selectProjectParkById(projectLand.getParkId());
            map.put("park",projectPark);
        }else {
            map.put("park",null);
        }
        return map;
    }

    @Override
    public int deleteProjectLandBySerialNumber(String spaceId) {
        ProjectLand projectLand = projectLandMapper.selectProjectLandByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectLand.getVrResource(),
                projectLand.getImgResource(),
                projectLand.getCoverResource(),
                projectLand.getVrcover(),
                projectLand.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("土地",projectLand.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectLandId(projectLand.getId());
        return projectLandMapper.deleteProjectLandById(projectLand.getId());
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);

    @Override
    public String importUser(List<ProjectLand> projectLands, boolean updateSupport, String operName) {
        if (StringUtils.isNull(projectLands) || projectLands.size() ==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;

        for (ProjectLand projectLand : projectLands) {
            if (projectLands.indexOf(projectLand)==0&&projectLand.getLandName().equals("土地名称")){
                continue;
            }
            count++;
            try {
                if (projectLand.getApprovalState()==null||STATE.contains(projectLand.getApprovalState())){
                    projectLand.setApprovalState(0L);
                }
                if (projectLand.getSupplyUserId()==null){
                    projectLand.setSupplyUserId(SecurityUtils.getUserId());
                }
                if (projectLand.getLandName()==null||projectLand.getLandName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少土地名称");
                    break;
                }
                projectLand.setCreateBy(SecurityUtils.getUsername());
                projectLand.setCreateTime(DateUtils.getNowDate());
                projectLandMapper.insertProjectLand(projectLand);
                successNum++;
                successMsg.append("<br/>" + successNum + "、土地 " + projectLand.getLandName() + " 导入成功");
            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、土地 " + projectLand.getLandName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectLand modal = projectLandMapper.selectProjectLandById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("土地名称：" + modal.getLandName() + "<w:br/>");
        stringBuffer.append("经济带：" + modal.getLandEconomic() + "<w:br/>");
        stringBuffer.append("区域：" + modal.getLandArea() + "<w:br/>");
        stringBuffer.append("空置土地位置：" + modal.getLandAddress() + "<w:br/>");
        stringBuffer.append("土地类别：" + modal.getLandType() + "<w:br/>");
        stringBuffer.append("总面积：" + modal.getLandAllSize() + "<w:br/>");
        stringBuffer.append("空置面积：" + modal.getLandFressSize() + "<w:br/>");
        stringBuffer.append("土地权属：" + modal.getLandTypeOwner() + "<w:br/>");
        stringBuffer.append("土地级别：" + modal.getLandLevel() + "<w:br/>");
        stringBuffer.append("土地整理情况：" + modal.getLandArrange() + "<w:br/>");
        stringBuffer.append("容积率：" + modal.getLandPlotRatio() + "<w:br/>");
        stringBuffer.append("建筑密度：" + modal.getLandBuildDensity() + "<w:br/>");
        stringBuffer.append("绿化率：" + modal.getLandGreenRate() + "<w:br/>");
        stringBuffer.append("土地出让方式：" + modal.getLandSell() + "<w:br/>");
        stringBuffer.append("土地价格：" + modal.getLandPrice() + "<w:br/>");
        stringBuffer.append("土地产业招商需求：" + modal.getLandInvestNeed() + "<w:br/>");
        stringBuffer.append("政策：" + modal.getLandPolic() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
